// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./router.config";
import axios from "axios";
import qs from 'qs';
//import App from "./App";
import store from "./store/index";
import "./assets/css/base.css"; //全局样式
import "./assets/css/swiper.css"; //swiper
import Lockr from "./assets/js/Lockr";
import "./util/rem";
import "./util/version";
import VueAwesomeSwiper from "vue-awesome-swiper";
import VueLazyload from "vue-lazyload";
import Velocity from "velocity-animate";
import config from "./config";
import Boom from './boom/boom';
import { vueBaberrage } from 'vue-baberrage'
import animated from 'animate.css';
import gd_imgTx from "./assets/images/gd_mr.png"
import fun from "./util/function";
import aes from "./util/Aes.js";
import less from 'less'
import VueLuckyCanvas from '@lucky-canvas/vue'
import Vconsole from 'vconsole'


Vue.prototype.$EventBus = new Vue()//丁一对于zxyhHeader组件被多层嵌套引用到home的场景, 添加了全局的eventbus
Vue.use(less)
Vue.use(VueLuckyCanvas)

let dzhconsole = window.sessionStorage.getItem('dzhconsole')
console.log('version 2023-04-03 11:14 ');
//new Vconsole()
if(dzhconsole =='dzhconsole'){
  new Vconsole()
}
fun.initSourcePlat().then(type=>{
  store.commit('setSourcePlat',type)
})
fun.initAxiosPlatform().then(type=>{
  store.commit('setAxiosPlat',type)
})
let u = navigator.userAgent;
console.log("navigator.userAgent:",u);
//监听sessionStorage 和localStorage值变化
Vue.prototype.$addStorageEvent = function (type, key, data) {
    // localStorage
  if (type === 1) {
    // 创建一个StorageEvent事件
    var newStorageEvent = document.createEvent('StorageEvent');
    const storage = {
      setItem: function (k, val) {
        localStorage.setItem(k, val);
        // 初始化创建的事件
        newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
        // 派发对象
        window.dispatchEvent(newStorageEvent);
      }
    }
    return storage.setItem(key, data);
  } else {
     // sessionStorage
    // 创建一个StorageEvent事件
    var newStorageEvent = document.createEvent('StorageEvent');
    const storage = {
      setItem: function (k, val) {
        sessionStorage.setItem(k, val);
        // 初始化创建的事件
        newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
        // 派发对象
        window.dispatchEvent(newStorageEvent);
      }
    }
    return storage.setItem(key, data);
  }
}

document.addEventListener("visibilitychange", function () {
  if (document.visibilityState == "visible") {
      store.dispatch("setAppVisible", true);
  }else if (document.visibilityState == "hidden") {
      store.dispatch("setAppVisible", false);
  }
})

axios.defaults.baseURL = "/api";
axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded";
window.needReload = false;
window.isInitVue = false;
Vue.use(vueBaberrage)
window.Boom = Boom;
window.fun = fun;
window.config = config;
var infiniteScroll = require('vue-infinite-scroll');
Vue.use(infiniteScroll)
window.imgError = () => {
  let img = event.srcElement;


  img.src = gd_imgTx;
  img.onerror = null;
}

import './assets/iconfont/iconfont.css';
import './assets/iconfont2/iconfont.css';
import './assets/iconfont3/iconfont.css';
import './boom/vant.css'
import './boom/vant.min.js'

//优雅地注册多个全局组件
import components from './plugins/components.js';
import Account from "./util/Account";
Vue.use(components);
Vue.use(VueLazyload);
Vue.use(animated);

let r = /^\b(http|https)\b:\/\/[a-z0-9\.:]+\/\??[\\\/\&=\-a-zA-Z0-9\._%\*\u4e00-\u9fa5]*#\/([a-zA-Z0-9]+)\/.*$/;
let exec = r.exec(location.href);
let channel = null
if (exec != null && typeof exec[2] != "undefined") {
  channel = exec[2]
  window.channel = channel
  console.log("channel is", channel)
} else if (location.href.indexOf('#/') == -1) {
    location.replace(location.origin + '/#' + location.href.replace(location.origin, ''))
}

//默认头像处理
window.imgTx = gd_imgTx;

Vue.use(VueLazyload);
Vue.use(VueRouter);
const router = new VueRouter({
  routes,
});

Vue.prototype.$myrouter = router

//window.router = router
if (!channel) {
  fun.errMsg('请确认正确的页面url,当前页面url:' + location.href)
}

window.isIos = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
window.isPc = navigator.platform.indexOf('Win') != -1

//全局使用swiper
Vue.use(VueAwesomeSwiper /* { default global options } */ );
let isVisitors = fun.GetUrlParam('isVisitors')
let source = fun.getQueryString('source');
if (source) {
  Lockr.set('source', source)
} else {
  let cSource = Lockr.get("source")
  if (cSource) {
    source = cSource
  }
}

if(!source && window.terminal.weixin){
  source = 'wx'
  Lockr.set('source', source)
}

Vue.config.productionTip = false; //阻止启动生产消息
Vue.prototype.$http = axios;
Vue.prototype.$qs = qs;
Vue.prototype.$store = store;
Vue.prototype.$lockr = Lockr;
Vue.prototype.$channel = channel;
Vue.prototype.$bus = new Vue();


let tmpToken = fun.getQueryString('token');
if (tmpToken && tmpToken.length == 32) {
  Account.setCacheToken(tmpToken)
  window.location.replace(fun.filterUrl('token'))
  //throw new Error('token filter');
} else {
  tmpToken = ''
}

let cacheToken = tmpToken || Account.getCacheToken()

if (location.hostname == 'guestsaas.yundzh.com') {
  store.dispatch("setYk", true);
} else {
  let qYk = fun.getQueryString('yk')

  if (qYk && qYk == '1') {
    store.dispatch("setYk", true);
  } else {
    store.dispatch("setYk", false);
  }
}


let appBrige = false

switch (channel) {
  case 'zxjt':
    if(window.terminal.isZxjtApp){
      appBrige = true
      window.setUserData = (data) =>{
        console.log("app setUserData",data)
      }

      window.setUserLoginStatus = (data) =>{
        console.log("setUserLoginStatus is ",data)
      }
      fun.appZxjtLoginInfoCallBack(source);
      // // app登录回调
      // window.setUserInfo = (data) =>{
      //   console.log("app setUserInfo",data)
 
      //   let  verStr = data.appVersion;
      //   if(window.terminal.ios){
      //     verStr = verStr.substring(4)
      //   }       
      //   const ver = window.versionCompare(verStr,'8.2.2');
      //   console.log('app版本---',ver);
      //   if(ver > -1){
      //     store.commit("setAppVersion", true);//app版本
      //     store.commit('setShowMarginTop',true);//设置头部
      //   }else{
      //     store.commit("setAppVersion", false);
      //     store.commit('setShowMarginTop',false);//设置头部
      //   }

      //   if(data && data.userId && data.userId.length > 0){
      //     store.commit('setZjzhInfo', data) // 全局同步用户信息
      //     console.log("userId is ", data.userId)
      //     let userId = data.userId
      //     let phone =  data.phone
      //     let avatar = data.avatar != undefined ? data.avatar : ''
      //     let nickName = data.nickName != undefined ? data.nickName : ''
      //     fun.appUserJoin(aes.encrypt(JSON.stringify({userId,phone,avatar,nickName})), channel, 'app').then(res => {}, err => {
      //       if (err == 'yk') {
      //         fun.buildYk(channel).then(resToken => {
      //           store.dispatch("setYk", true)
      //           fun.initVue(resToken, channel, source)
      //         }, err => {
      //           fun.gotoBusyPage()
      //         })
      //       }
      //     })
      //   }else{
      //     fun.buildYk(channel).then(resToken => {
      //       store.dispatch("setYk", true)
      //       fun.initVue(resToken, channel, source)
      //     }, err => {
      //       fun.gotoBusyPage()
      //     })
      //   }
      // }
      // 获取未登录态用户信息
      if(window.terminal.isZxjtAndroid){
        KDS_Native.getUserInfo('')
		    KDS_Native.getAppVersion()
      }else if(window.terminal.isZxjtIos){
        window.webkit.messageHandlers.getUserInfo.postMessage('')
		    window.webkit.messageHandlers.getAppVersion.postMessage('')
      }
    }

    break;
  case 'zxjtqh':
    if (window.terminal.isZxjtqhApp) {
      window.topmargin = Number(fun.getQueryString('topmargin',false))//状态栏高度
      if(window.topmargin){
        window.localStorage.setItem('topMargin',window.topmargin)
      }
      const urlModuleName = fun.getQueryString('moduleName',false)
      window.localStorage.setItem('urlModuleName',urlModuleName)
      fun.loadBridge('/static/zxjtqh/externalAPP.js', (() => {
        const paramMap = {
          "funcNo":"50100",//通知原生页面加载完成
          "moduleName":urlModuleName || 'liveHome'
        }
        window.callMessageNative(paramMap)
        window['function60200'] = (res)=>{//登陆页面回调参数
          if(res.flag == '0'){//登录
            fun.getZxjtqhCacheData()
          }
        }
      }));
    }


    break;
  default:
    if (!source && (window.terminal.ios || window.terminal.android)) {
      source = "app"
    }
    break;
}

if (!appBrige) {
  init(cacheToken).then(tokenRes => {
    fun.initVue(tokenRes, channel, source)
  }, err => {
    switch (err) {
      case 'noToken':
        if(channel =='zxjt'){
          let buildUrl = config.WX_REDIRECT_SERVER + '?appId=' + config.WX_APP_ID + '&url=' +
            encodeURIComponent(config.API_HOST+'auth/wxUserAccess?channel='+channel+'&url='+encodeURIComponent(location.href))
          let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.WX_APP_ID +
            '&redirect_uri=' + encodeURIComponent(buildUrl) +
            '&response_type=code&scope=snsapi_userinfo&state='+location.hostname+'#wechat_redirect'
          window.location.replace(url)
        }else if(channel =='zxjtqh'){
          let buildUrl = config.API_HOST+'auth/sync?channel='+ channel + '&url='+encodeURIComponent(location.href)
          let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.getWxCfg(channel).APP_ID +
            '&redirect_uri=' + encodeURIComponent(buildUrl) +
            '&response_type=code&scope=snsapi_userinfo&state='+location.hostname+'#wechat_redirect'
          window.location.replace(url)
        }
        else {
          fun.gotoBusyPage()
        }
        break;
      case 'gotoBuildYk':
        fun.buildYk(channel).then(resToken => {
          store.dispatch("setYk", true)
          fun.initVue(resToken, channel, source)
        }, err => {
          fun.gotoBusyPage()
        })
        break;
      case 'gdEx':
        Account.gotoGdexAuth2()
        break;
      case 'buildYk err':
        fun.gotoBusyPage()
        break;
      case 'err':
        fun.errMsg("抱歉，游客模式暂时关闭，请稍后重试谢谢！")
        break;
      default:
        fun.gotoBusyPage()
    }
  })
}
window.entryUrl = ''

router.beforeEach((to, from, next) => {
  //if (to.meta.title) {
  //  document.title = to.meta.title
  //}else{
  //	document.title = '\u200E'
  //}
  to.meta.refer = from.fullPath == '/' ? '/' + channel + '/home' : from.fullPath
  next()
})
router.afterEach(to => {
  if (isIos) { // IOS
    if (entryUrl == '') {
      entryUrl = window.location.href.split('#')[0] // 将后面的参数去除
    }
  } else { // 安卓
    entryUrl = window.location.href.split('#')[0]
  }

  if (to.path.indexOf("live_particulars") == -1) {
    //console.log("dispatch video")
    store.dispatch("closeIm", 0);
    store.dispatch("setLiveBackVideoSrc", "http://dzh");
  };
});

function init(tokenParam) {
  return new Promise((resolve, reject) => {
    if (!tokenParam) {
      let authParam = fun.getQueryString("params", false)

      let isYk = store.state.isYk

      if (authParam) {
        let params = new URLSearchParams();
        if (source) {
          params.append('source', source);
        }
        params.append('channel', channel);
        params.append('authParam', authParam);
        //params.append('areaName',fun.getQueryString('areaName',false))
        fun.buildChannelAc(params).then(r => {
          source = r.source
          Lockr.set('source', source)
          store.dispatch("setYk", r.isYk);
          return resolve(r.token)
        }, err => {
          reject("gotoBuildYk")
        })
      }else if (isYk || fun.getPlatform() != 'wx') {
        reject("gotoBuildYk")
      } else {
        reject("noToken")
      }
    } else {
      resolve(tokenParam);
    }
  })
}


function onload() {
  document.addEventListener('deviceready', () => {
    window.bridgeReady = true
    console.log('桥接口初始化成功')
  }, false)
}

function onerror() {
  console.log('桥接口初始化失败')
}
//下面代码为了解决点击当前路由报错   Uncaught (in promise)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
	  window['setAppVersion'] = (res) =>{
		  let version = JSON.parse(res).appVersion;      
	  }

// 是否为三方外链跳转 zxjk  jkcgjr
if(!!fun.GetNewUrlParam('isJump')){
  window.sessionStorage.setItem('isJump', fun.GetNewUrlParam('isJump'));
  if(fun.GetNewUrlParam('toJump')){
    window.sessionStorage.setItem('toJump', fun.GetNewUrlParam('toJump'));
  }
}
